﻿using System.Collections.Generic;

namespace System.Linq.Functional
{
    public static class GenerateExtensions
    {
        // F# Seq.generate
        public static IEnumerable<TResult> Generate<T, TResult>(Func<T> opener, Func<T, Option<TResult>> generator, Action<T> closer)
        {
            var openerResult = opener();

            while (true)
            {
                var res = generator(openerResult);
                if (res.IsNone)
                {
                    closer(openerResult);
                    yield break;
                }

                yield return res.Value;
            }
        }

        public static IEnumerable<TResult> GenerateUsing<T, TResult>(Func<T> opener, Func<T, Option<TResult>> generator) where T : IDisposable
        {
            return Generate(opener, generator, x => x.Dispose());
        }
    }
}
